package com.bigfans.catalogservice.api.interceptor;

import com.bigfans.Constants;
import com.bigfans.framework.Applications;
import com.bigfans.framework.CurrentUser;
import com.bigfans.framework.annotations.NeedLogin;
import com.bigfans.framework.utils.JwtUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 
 * @Title:
 * @Description: 登录拦截器,如果被请求的方法上有@NeedLogin注解,那么就会做登录验证
 * @author lichong
 * @date 2016年1月27日 上午8:48:52
 * @version V1.0
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if(cookie.getName().equals(Constants.TOKEN.KEY_NAME)){
					String token = cookie.getValue();
					Map<String, Object> claims = JwtUtils.parse(token, "bigfans");
					CurrentUser currentUser = new CurrentUser();
					currentUser.setAccount((String) claims.get("account"));
					currentUser.setInvalid((Boolean) claims.get("invalid"));
					currentUser.setIp((String) claims.get("ip"));
					currentUser.setLoginTime(new Date((long)claims.get("loginTime")) );
					currentUser.setNickname((String) claims.get("nickname"));
					currentUser.setUid((String) claims.get("uid"));
					Applications.setCurrentUser(currentUser);
				}
			}
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		NeedLogin loginAnno = handlerMethod.getMethodAnnotation(NeedLogin.class);
		CurrentUser currentUser = Applications.getCurrentUser();
		// 如果已经登录
		if(currentUser != null){
			return true;
		}
		// 当前请求不需要登录
		if (loginAnno == null) {
			return true;
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		Applications.clearCurrentUser();
	}

}
